//
//  PKSwift.swift
//  SHTelemarketing
//
//  Created by pinkjoker on 2021/1/27.
//


import Foundation
import SnapKit
import RxSwift
import RxOptional
import RxCocoa
import SnapKit
import RxDataSources
import Alamofire
import Hero
import ObjectMapper
import NSObject_Rx
import Moya
import UIKit


struct ScreenAdapter {
    static let baseWidth: CGFloat = 375.0
    static let baseHeight: CGFloat = 812.0
    
    static var scaleX: CGFloat {
        UIScreen.main.bounds.width / baseWidth
    }
    
    static var scaleY: CGFloat {
        UIScreen.main.bounds.height / baseHeight
    }
    
    static func x(_ value: CGFloat) -> CGFloat {
        value * scaleX
    }
    
    static func y(_ value: CGFloat) -> CGFloat {
        value * scaleY
    }
    
    static func rect(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> CGRect {
        CGRect(x: x * scaleX, y: y * scaleY, width: width * scaleX, height: height * scaleY)
    }
}


struct DeviceHelper {
    
    /// 状态栏高度（iOS 13+ 通过 Scene 来获取）
    static var statusBarHeight: CGFloat {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .first?.statusBarManager?.statusBarFrame.height ?? 0
        } else {
            return UIApplication.shared.statusBarFrame.height
        }
    }

    /// 导航栏高度（不包含状态栏）
    static var navigationBarHeight: CGFloat {
        return 44.0
    }

    /// 状态栏 + 导航栏总高度
    static var navigationFullHeight: CGFloat {
        return statusBarHeight + navigationBarHeight
    }

    /// TabBar 高度（iPhone X 及以上设备为 83，其他为 49）
    static var tabBarHeight: CGFloat {
        return isFullScreenDevice ? 83.0 : 49.0
    }

    /// 底部安全区域高度（适配刘海屏）
    static var bottomSafeAreaHeight: CGFloat {
        if #available(iOS 11.0, *) {
            return UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0
        } else {
            return 0
        }
    }

    /// 是否是刘海屏（全屏设备）
    static var isFullScreenDevice: Bool {
        if #available(iOS 11.0, *) {
            return UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0 > 0
        } else {
            return false
        }
    }

    /// 屏幕宽度
    static var screenWidth: CGFloat {
        return UIScreen.main.bounds.width
    }

    /// 屏幕高度
    static var screenHeight: CGFloat {
        return UIScreen.main.bounds.height
    }
}

let kWidth =   UIScreen.main.bounds.size.width
let  kHeight =  UIScreen.main.bounds.size.height



final class AppContext {

    static let shared = AppContext()

    private init() {}

    // MARK: - 当前 KeyWindow

    var currentWindow: UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .flatMap { $0.windows }
                .first { $0.isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }
    }

    // MARK: - 顶层 ViewController

    var topViewController: UIViewController? {
        guard let root = currentWindow?.rootViewController else { return nil }
        return AppContext.topViewController(for: root)
    }

    private static func topViewController(for root: UIViewController) -> UIViewController {
        if let presented = root.presentedViewController {
            return topViewController(for: presented)
        } else if let nav = root as? UINavigationController, let visible = nav.visibleViewController {
            return topViewController(for: visible)
        } else if let tab = root as? UITabBarController, let selected = tab.selectedViewController {
            return topViewController(for: selected)
        } else {
            return root
        }
    }

    // MARK: - 显示全局错误提示

    func showGlobalError(message: String, title: String = "错误") {
        guard let vc = topViewController else { return }
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(.init(title: "确定", style: .default))
        vc.present(alert, animated: true)
    }

    // MARK: - 显示全局 HUD（可扩展为 MBProgressHUD 等）

    func showGlobalLoading() {
        guard let window = currentWindow else { return }
        let indicator = UIActivityIndicatorView(style: .large)
        indicator.center = window.center
        indicator.tag = 9999
        indicator.startAnimating()
        window.addSubview(indicator)
    }

    func hideGlobalLoading() {
        currentWindow?.viewWithTag(9999)?.removeFromSuperview()
    }
}






//let kTextBlueColor = UIColor.jk_color(withHexString: "006BF1")
//let kButtonBLueColor = UIColor.jk_color(withHexString: "1879f2")
//let kTextBlackColor = UIColor.jk_color(withHexString: "333333")
//let kUnderColor = UIColor.jk_color(withHexString: "eeeeee")
let kBlackColor = UIColor.black
let kBlueColor = UIColor.blue
let kWhiteColor = UIColor.white
let kMainColor = RGBAColor(r: 7, g: 130, b: 254, a: 1)
let KGrayColor = RGBAColor(r: 195, g: 195, b: 195, a: 1)
//let kBlueLightColor = UIColor.jk_color(withHexString: "1E7BF2")
let kGrayLightColor = UIColor.lightGray

func RGBAColor(r : CGFloat, g : CGFloat, b : CGFloat, a : CGFloat) -> UIColor? {
    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a))
}

func HexColor (hex : String, a : CGFloat) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    if (cString.hasPrefix("#")) {
        cString = (cString as NSString).substring(from: 1)
    }
    let rString = (cString as NSString).substring(to: 2)
    let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
    let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
    var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
    Scanner(string: rString).scanHexInt32(&r)
    Scanner(string: gString).scanHexInt32(&g)
    Scanner(string: bString).scanHexInt32(&b)
    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
}


func printG<T>(_ message: T,
               file: String = #file,
               method: String = #function,
               line: Int = #line) {
    #if DEBUGLOG
        print("\((file as NSString).lastPathComponent)[\(line)]---🐷-🐷---\(method):\n \(message)")
    #endif
}

